package cn.cumulomq.service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;

import cn.ait.umc.logicalchannel.AFTNProtocolParameter;
import cn.ait.umc.logicalchannel.SerialInterface;
import cn.ait.umc.logicalchannel.TCPInterface;
import cn.ait.umc.logicalchannel.amtcp.client.AMTCPClientInterface;
import cn.cumulomq.MQXMain;
import cn.cumulomq.dao.ChannelConfigDao;
import cn.cumulomq.db.ConfigDB;
import cn.cumulomq.entity.ChannelConfig;
import cn.cumulomq.utils.JsonMapper;

/**
 * 管理AFTN信道通信参数
 * @author maxuedong
 *
 */
public class AftnChannelService {

	private Logger logger = Logger.getLogger(AftnChannelService.class);
	
	public ChannelConfig get(String id){
		ChannelConfig cc = null;
		try{
			SqlSession session = ConfigDB.getSessionFactory().openSession();
			ChannelConfigDao channelConfigDao = session.getMapper(ChannelConfigDao.class);
			cc = channelConfigDao.get(id);
			session.close();
		}catch(Exception e){
			logger.error(e);
		}
		if(cc!=null)json2parm(cc);
		return cc;		
	}
	/**
	 * 添加修改信道，如果
	 * @param channelConfig
	 * @return
	 */
	public boolean save(ChannelConfig channelConfig){
		try{
			parm2json(channelConfig);
			SqlSession session = ConfigDB.getSessionFactory().openSession();
			ChannelConfigDao channelConfigDao = session.getMapper(ChannelConfigDao.class);
			if(channelConfig.getId()==null||"".equals(channelConfig.getId())){
				channelConfig.setId(UUID.randomUUID().toString());
				channelConfigDao.insert(channelConfig);
				try {
					MQXMain.getInstance().connectDMHS(channelConfig);
				} catch (Throwable e) {
					logger.warn("Connect DMHS error.",e);
				}
			}else{
				channelConfigDao.update(channelConfig);
				//重新连接
				try {
					MQXMain.getInstance().disConnectDMHS(channelConfig);
					MQXMain.getInstance().connectDMHS(channelConfig);
				} catch (Throwable e) {
					logger.warn("Reconnect DMHS error.",e);
				}
			}
			session.commit();
			session.close();
		}catch(Exception e){
			logger.error(e);
			return false;
		}
		return true;
	}
	
	/**
	 * 删除信道
	 * @param channelConfig
	 * @return
	 */
	public boolean delete(ChannelConfig channelConfig){
		try{
			SqlSession session = ConfigDB.getSessionFactory().openSession();
			ChannelConfigDao channelConfigDao = session.getMapper(ChannelConfigDao.class);
			channelConfigDao.delete(channelConfig);
			session.commit();
			session.close();
			//断开连接
			try {
				MQXMain.getInstance().disConnectDMHS(channelConfig);
			} catch (Throwable e) {
				logger.warn("Disconnect DMHS error.",e);
			}
		}catch(Exception e){
			logger.error(e);
			return false;
		}
		return true;
	}
	/**
	 * 获取信道列表
	 * @return
	 */
	public List<ChannelConfig> list(ChannelConfig channelConfig){
		List<ChannelConfig> res = new ArrayList<ChannelConfig>();
		try{
			SqlSession session = ConfigDB.getSessionFactory().openSession();
			ChannelConfigDao channelConfigDao = session.getMapper(ChannelConfigDao.class);
			res = channelConfigDao.list(channelConfig);
			session.close();
		}catch(Exception e){
			logger.error(e);
		}
		for(ChannelConfig cc:res){
			json2parm(cc);
		}
		return res;	
	}
	/**
	 * 将接口参数对象以JSON方式存储
	 * @param channelConfig
	 */
	private void parm2json(ChannelConfig channelConfig){
		JsonMapper jm = JsonMapper.getInstance();
		channelConfig.setProtocolParmJson(jm.toJson(channelConfig.getMessageProtocolParameter()));
		if(channelConfig.getCommType()==ChannelConfig.COMMTYPE_AMTCP){
			channelConfig.setInterfaceJson(jm.toJson(channelConfig.getAmTcpInterface()));
		}else if(channelConfig.getCommType()==ChannelConfig.COMMTYPE_SERIAL){
			channelConfig.setInterfaceJson(jm.toJson(channelConfig.getSerialInterface()));
		}else if(channelConfig.getCommType()==ChannelConfig.COMMTYPE_TCP){
			channelConfig.setInterfaceJson(jm.toJson(channelConfig.getTcpInterface()));
		}
	}
	/**
	 * 将存储的JSON转为接口参数对象
	 * @param channelConfig
	 */
	private void json2parm(ChannelConfig channelConfig){
		JsonMapper jm = new JsonMapper();
		channelConfig.setMessageProtocolParameter(jm.fromJson(channelConfig.getProtocolParmJson(), AFTNProtocolParameter.class));
		
		if(channelConfig.getCommType()==ChannelConfig.COMMTYPE_AMTCP){
			channelConfig.setAmTcpInterface(jm.fromJson(channelConfig.getInterfaceJson(),AMTCPClientInterface.class));
		}else if(channelConfig.getCommType()==ChannelConfig.COMMTYPE_SERIAL){
			channelConfig.setSerialInterface(jm.fromJson(channelConfig.getInterfaceJson(),SerialInterface.class));
		}else if(channelConfig.getCommType()==ChannelConfig.COMMTYPE_TCP){
			channelConfig.setTcpInterface(jm.fromJson(channelConfig.getInterfaceJson(),TCPInterface.class));
		}
		
	}
}
